package com.estronger.shopmanage.ui.home;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B1Login;
import com.estronger.shopmanage.bean.B2Guide;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.manager.PopManager;
import com.estronger.shopmanage.ui.MainActivity;
import com.estronger.shopmanage.utils.MD5Utils;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.PrefUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.RoundImageView;
import com.lidroid.xutils.http.RequestParams;
import com.orhanobut.hawk.Hawk;
import com.soonfor.evaluate.tools.CommonUtils;
import com.soonfor.evaluate.tools.ImageUtils;
import com.soonfor.evaluate.tools.UserInfo;
import com.tbruyelle.rxpermissions2.Permission;

import java.util.ArrayList;

import cn.jesse.nativelogger.NLogger;


public class LoginActivity extends BaseActivity {
	private MyApplication app;
	private PopManager popUtil;
	private FrameLayout fl_root;
	private EditText ed_itName, ed_itPassword;
	private String name = "", password = "", encodePassword = "";
	private RoundImageView company_logo;
	private String logo, logodesc;
	private TextView tv_server;
	private RelativeLayout rlfBack;
	private ImageView imgfCover;

	@Override
	protected void init() {
		setImmersive();
		app = MyApplication.getApplication();
		PermissionUtils.getInstance().requestPromisssions(this, new PermissionUtils.AcceptListener() {
					@Override
					public void grante() {}

					@Override
					public void denial(Permission permission) {
						NLogger.e("您拒绝了相关权限:"+permission);
					}

					@Override
					public void fail() {}
				},
				Manifest.permission.CAMERA,
				Manifest.permission.CALL_PHONE,
				Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.ACCESS_WIFI_STATE,
				Manifest.permission.ACCESS_FINE_LOCATION,
				Manifest.permission.RECORD_AUDIO,
				Manifest.permission.READ_PHONE_STATE);
	}

	@Override
	protected void initView() {
		fl_root = (FrameLayout) View.inflate(this, R.layout.activity_login, null);
		setContentView(fl_root);
		ed_itName = (EditText) findViewById(R.id.login_name_edit);
		ed_itPassword = (EditText) findViewById(R.id.login_password_edit);
		company_logo = (RoundImageView) findViewById(R.id.company_logo);
		tv_server = (TextView) findViewById(R.id.server_tv1);
		rlfBack = (RelativeLayout) findViewById(R.id.rlfBack);
		imgfCover = findViewById(R.id.imgfCover);
		popUtil = new PopManager(this, imgfCover);
		String name = PrefUtils.getString(this, "userName", "");
		ed_itName.setText(name);
		if(name.length()>0) {
			ed_itName.setSelection(name.length());
		}
		ed_itPassword.setText(PrefUtils.getString(this, "userPwd", ""));
		rlfBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				MyApplication.isLoginToServer = true;
				Intent intent = new Intent(LoginActivity.this, ServerActivity.class);
				LoginActivity.this.startActivity(intent);
				finish();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		//201707130947加的
//		if (TextUtils.isEmpty(app.getSERVER_URL())) {
//			startActivity(new Intent(this, ServerActivity.class));
//		}else{
		logo = PrefUtils.getString(this, "logo", "");
		logodesc = PrefUtils.getString(this, "logodesc", "");
		MyApplication.imageLoader.displayImage(logo, company_logo);
		tv_server.setText(logodesc);
		new Thread(new Runnable() {
			@Override
			public void run() {
				RequestParams params = new RequestParams();
				params.addBodyParameter("sf_action", "getlogo");
				connect(params, NetManager.ADS);
			}
		}).start();
	}

	public void showPop() {
		if (popUtil.getLoginPop() == null) {
			popUtil.initLoginPop();
		}
		if (popUtil.isLoginPopShowing())
			popUtil.hideLoginPop();
		popUtil.showLoginPop(fl_root, true);
	}

	public void login(View view) {
		name = ed_itName.getText().toString().trim();
		password = ed_itPassword.getText().toString().trim();
		if (TextUtils.isEmpty(name)) {
			Toast.show(this, "请先输入用户名", 2000);
			return;
		}
		if (TextUtils.isEmpty(password)) {
			Toast.show(this, "密码不能为空", 2000);
			return;
		} else {
			encodePassword = MD5Utils.md5Password(password);
		}
		if (TextUtils.isEmpty(MyApplication.phone_id)) {
			MyApplication.phone_id = name;// 有部分山寨机没有android.os.Build.SERIAL
		}
		if (!NetUtils.isNetworkConnected(LoginActivity.this)) {
			Toast.show(LoginActivity.this, "当前无网络链接！", Toast.LENGTH_SHORT);
			return;
		}
		showDialog("登录中...", false);
		RequestParams params = new RequestParams();
		params.addBodyParameter("regid", CommonUtils.getIMEI(LoginActivity.this));
		params.addBodyParameter("usercode", name);
		params.addBodyParameter("password", encodePassword);
		params.addBodyParameter("sf_action", "login");
		connect(params, NetManager.LOGIN);
	}

	@Override
	protected void onNetErorr(int code, String msg) {
		super.onNetErorr(code, msg);
	}


	@Override
	protected void onNetSuccess(int code, String result) {
		super.onNetSuccess(code, result);
		if (code == NetManager.ADS) {
			try {
				B2Guide bean = gson.fromJson(result, B2Guide.class);
				if (bean.success) {
					PrefUtils.setString(this, "firstPic", bean.data.getNav0());
					String newlog = bean.data.getLogo();
					if (!newlog.equals("") && !newlog.equals(logo)) {
						PrefUtils.setString(this, "logo", newlog);
						MyApplication.imageLoader.displayImage(newlog, company_logo);
					}
					String newlogdesc = bean.data.getLogodesc();
					if (!newlogdesc.equals("") && !newlog.equals(logodesc)) {
						PrefUtils.setString(this, "logodesc", newlogdesc);
						tv_server.setText(newlogdesc);
					}
				}
			}catch (Exception e){}

		} else if (NetManager.LOGIN == code) {
			try {
				MyApplication.login = gson.fromJson(result, B1Login.class);
				if (MyApplication.login.success) {
					PrefUtils.setBoolean(this, "isLogin", true);
					PrefUtils.setString(this, "loginData", result);
					try{
						PrefUtils.setString(this, "userName", MyApplication.login.data.getUsercode());
					}catch (Exception e0){
						PrefUtils.setString(this, "userName", name);
					}
					PrefUtils.setString(this, "userPwd", password);
					Hawk.put(UserInfo.LOGIN_USERINFO, MyApplication.login.data);
					startActivity(new Intent(this, MainActivity.class));
					finish();
				} else if (MyApplication.login.msgcode == 10004) {
					if (popUtil.getLoginPop() == null) {
						popUtil.initLoginPop();
					}
					if (popUtil.isLoginPopShowing()) {
						popUtil.hideLoginPop();
					} else {
						popUtil.showLoginPop(fl_root, true);
					}
				} else {
					if (popUtil.getLoginPop() == null) {
						popUtil.initLoginPop();
					}
					if (popUtil.isLoginPopShowing()) {
						popUtil.hideLoginPop();
					} else {
						popUtil.showLoginPop(fl_root, false);
					}
				}
			}catch (Exception e){
				MyApplication.login = gson.fromJson(result, B1Login.class);
			}

		}else if (NetManager.FGET_PSWD == code) {
			BeanBase bean = gson.fromJson(result, BeanBase.class);
			Toast.show(this, bean.msg, 2000);
		}
	}
	public void forgetPassword(View view) {
		name = ed_itName.getText().toString().trim();
		RequestParams params = new RequestParams();
		params.addBodyParameter("usercode", name);
		params.addBodyParameter("sf_action", "getpwd");
		connect(params, NetManager.FGET_PSWD);
		popUtil.hideLoginPop();
	}
	@Override
	protected void onActivityResult(int request, int result, Intent data) {
		super.onActivityResult(request, result, data);
		ArrayList<String> mSelectPath = ImageUtils.getPicPaths(data);
		if (mSelectPath.size()>0 && !TextUtils.isEmpty(mSelectPath.get(0))) {
			PrefUtils.setString(this, "clogo", mSelectPath.get(0));
			Bitmap file = BitmapFactory.decodeFile(mSelectPath.get(0));
			company_logo.setImageBitmap(file);
		}
	}
	@Override
	public void onBackPressed() {
		finish();
	}

}
